package com.zl.iot.docking.util;

import com.zl.iot.docking.exception.ZLExcep;

import java.lang.reflect.Method;

/**
 * @author chenzy
 * @since 2023/6/26
 * copy org.apache.logging.log4j.util.Base64Util
 **/
public final class Base64Util {

    private static Method encodeMethod = null;
    private static Object encoder = null;

    static {
        try {
            Class<?> clazz = LoaderUtil.loadClass("java.util.Base64");
            Class<?> encoderClazz = LoaderUtil.loadClass("java.util.Base64$Encoder");
            Method method = clazz.getMethod("getEncoder");
            encoder = method.invoke(null);
            encodeMethod = encoderClazz.getMethod("encodeToString", byte[].class);
        } catch (Exception ex) {
            try {
                Class<?> clazz = LoaderUtil.loadClass("javax.xml.bind.DataTypeConverter");
                encodeMethod = clazz.getMethod("printBase64Binary");
            } catch (Exception ex2) {
//                LowLevelLogUtil.logException("Unable to create a Base64 Encoder", ex2);
                ZLExcep.throwError("Unable to encode String",ex);
            }
        }
    }

    private Base64Util() {
    }

    public static String encode(String str) {
        if (str == null) {
            return null;
        }
        byte [] data = str.getBytes();
        if (encodeMethod != null) {
            try {
                return (String) encodeMethod.invoke(encoder, data);
            } catch (Exception ex) {
//                throw new LoggingException("Unable to encode String", ex);
                ZLExcep.throwError("Unable to encode String",ex);
            }
        }
        throw ZLExcep.error("No Encoder, unable to encode string");
    }
}
